#include<iostream>
#include<string>
#include<vector>
#include<unistd.h>
#include<pthread.h>
using namespace std;
#define NUM 4 //四个线程同时抢票
//模拟抢票过程
class threadDate
{
    public:
    threadDate(int number,pthread_mutex_t *lock)
    {
        threadName="thread-"+to_string(number);
        lock_=lock;
    }
    public:
    string threadName;
    pthread_mutex_t *lock_;
};
string toHex(pthread_t tid)
{
   char buffer[1024];
   snprintf(buffer,sizeof(buffer),"0x%x",tid);
   return buffer;
}
int ticket=1000;
void *getTicket(void *args)
{
    threadDate* td=static_cast<threadDate*>(args);//强转
    const char*name=td->threadName.c_str();
    while(true)
    {
        pthread_mutex_lock(td->lock_);//加锁
        if(ticket>0)
        {
            usleep(1000);
            printf("who=%s,get a ticket: %d\n",name,ticket);
            ticket--;
            pthread_mutex_unlock(td->lock_);//解锁
        }
        else
        {
            pthread_mutex_unlock(td->lock_);//解锁
            break;
        }
        usleep(17);//抢票后的后续工作
        
    }
    printf("%s.....exit\n",name);
   return nullptr;
}
int main()
{
    pthread_mutex_t lock;//创建锁
    pthread_mutex_init(&lock,nullptr);//局部锁需要调用函数初始化
    vector<pthread_t>tids;
    vector<threadDate*> thread_dates;
    for(int i=1;i<=NUM;i++)
    {
        pthread_t tid;
        threadDate *td=new threadDate(i,&lock);
        thread_dates.push_back(td);
        pthread_create(&tid,nullptr,getTicket,(void*)td);
        tids.push_back(tid);
    }
    for(int i=0;i<tids.size();i++)
    {
       pthread_join(tids[i],nullptr);//等待线程，不取返回值
       delete thread_dates[i];//释放堆空间
    }
    pthread_mutex_destroy(&lock);//销毁锁
    return 0;
}
